﻿using System.Collections.ObjectModel;
using System.Net.Http;
using System.Net.Http.Json;
using System.Windows;

namespace ServerManager.Models
{
    public class MachineViewModel : ViewModelBase
    {
        public RelayCommand CloseAllCommand { get; }
        public ObservableCollection<MachineInfo> Machines
        {
            get => machines;
            private set
            {
                if (machines != value)
                {
                    machines = value;
                    OnPropertyChanged(nameof(Machines));
                }
            }
        }
        private Timer _timer;
        private volatile bool isFetching = false;
        private HttpClient _httpClient;
        private ObservableCollection<MachineInfo> machines;
        private bool _canExcute = false;
        public Uri ServerUrl {  get; set; }

        public MachineViewModel()
        {
            Machines = new ObservableCollection<MachineInfo>();
            CloseAllCommand = new RelayCommand(ExecuteClick, CanClick);
            _httpClient = new HttpClient();
            _httpClient.BaseAddress =ServerUrl;
            _httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
            _timer = new Timer(FetchData, null, 5000, 5000);

        }

        private async void FetchData(object? state)
        {
            try
            {
                if (isFetching) { return; }
                isFetching = true;

                var result = await _httpClient.GetAsync("/Center");
                Machines.Clear();
                _canExcute=false;
                CloseAllCommand.RaiseCanExecuteChanged();

                if (result != null && result.IsSuccessStatusCode)
                {
                    var data = await result.Content.ReadFromJsonAsync<IEnumerable<MachineInfo>>();
                    if (data == null) { return; }
                    foreach (var item in data)
                    {
                        Machines.Add(item);

                    }
                }
                _canExcute = true;
                CloseAllCommand.RaiseCanExecuteChanged();

            }
            catch (Exception er)
            {


            }
            finally
            {
                isFetching = false;
            }


        }

        private async void ExecuteClick(object args)
        {
            if (Machines.Any() && MessageBox.Show("您确定要关闭所有电脑吗？", "提示", MessageBoxButton.OKCancel, MessageBoxImage.Question) == MessageBoxResult.OK)
            {
                foreach (var item in Machines.ToList())
                {
                    var httpClient = new HttpClient();
                    httpClient.BaseAddress = new Uri($"http://{item.IpAddress}:8888");
                    httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
                   var result= await httpClient.PostAsync("/shutdown", null);
                }

            }
        }
        private bool CanClick(object args)
        {
            return _canExcute;
        }
    }
}
